package hash_map;

import java.util.*;

public class leetcode49 {
    public static void main(String[] args) {
        String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> result = groupAnagrams(strs);
        for (List<String> strings : result) {
            System.out.println(strings);
        }
    }

    public static List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();

        for (String s : strs) {
            // 将字符串转换为字符数组并排序
            char[] chars = s.toCharArray();
            Arrays.sort(chars);
            String key = new String(chars); // 排序后的字符串作为key

            // 如果key不存在，新建一个列表
            if (!map.containsKey(key)) {
                map.put(key, new ArrayList<>());
            }
            // 将原始字符串添加到对应的列表中
            map.get(key).add(s);
        }

        return new ArrayList<>(map.values());
    }
}
